# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/4/28
import os

from submodules.common.lib.log_ import get_logger

logger = get_logger(__file__)

# 获取相关进程信息
script_name = "daily_task.py"
cmd_tmp = f"wmic process get Caption,CommandLine,ExecutablePath,ProcessId|findstr {script_name}"
logger.info(cmd_tmp)
cmd_res = os.popen(cmd_tmp).read()

# 结构化进程信息
process_info_raw_list = cmd_res.split("\n")
logger.info(process_info_raw_list)
process_info_list = []
for process_info_raw in process_info_raw_list:
    if process_info_raw.__len__() > 0:
        process_item_info_list = []
        process_item_info_list_tmp = process_info_raw.split(" ")
        for process_item_info_tmp in process_item_info_list_tmp:
            if process_item_info_tmp != "":
                process_item_info_list.append(process_item_info_tmp)

        process_info_list.append(process_item_info_list)
        process_info_list = sorted(process_info_list, key=lambda x: x[-1], reverse=True)

logger.info(process_info_list)

# 按pid停止进程
for process_info in process_info_list:
    try:
        pid = process_info[-1]
        cmd_tmp = f"taskkill /F /T /PID {pid}"
        logger.info(cmd_tmp)
        res = os.popen(cmd_tmp).read()
        logger.info(res)
    except:
        pass
